<template>
  <div class="grade-statistics">
    <div class="page-header">
      <h2>成绩统计分析</h2>
      <p>查看所有学生成绩数据和统计图表</p>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :inline="true" :model="searchParams" class="demo-form-inline">
        <el-form-item label="学年">
          <el-select v-model="searchParams.academicYear" placeholder="请选择学年" clearable>
            <el-option label="2024-2025" value="2024-2025" />
            <el-option label="2023-2024" value="2023-2024" />
            <el-option label="2022-2023" value="2022-2023" />
          </el-select>
        </el-form-item>
        <el-form-item label="学期">
          <el-select v-model="searchParams.semester" placeholder="请选择学期" clearable>
            <el-option label="第一学期" value="第一学期" />
            <el-option label="第二学期" value="第二学期" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input v-model="searchParams.courseName" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input v-model="searchParams.studentName" placeholder="请输入学生姓名" clearable />
        </el-form-item>
        <el-form-item label="教师姓名">
          <el-input v-model="searchParams.teacherName" placeholder="请输入教师姓名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" :value="0" />
            <el-option label="已保存" :value="1" />
            <el-option label="已送审" :value="2" />
            <el-option label="已审核通过" :value="3" />
            <el-option label="已审核退回" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchGrades">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="refreshStatistics">刷新统计</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card>
            <div class="stat-card">
              <div class="stat-icon total">
                <el-icon><Tickets /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ statistics.totalStudents || 0 }}</div>
                <div class="stat-label">总成绩记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="stat-card">
              <div class="stat-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ statistics.pendingCount || 0 }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="stat-card">
              <div class="stat-icon approved">
                <el-icon><Select /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ statistics.approvedCount || 0 }}</div>
                <div class="stat-label">已通过</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="stat-card">
              <div class="stat-icon rejected">
                <el-icon><Close /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ statistics.rejectedCount || 0 }}</div>
                <div class="stat-label">已退回</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 成绩等级分布饼图 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <h3>成绩等级分布</h3>
            </template>
            <div ref="gradeDistributionChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        
        <!-- 状态分布饼图 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <h3>成绩状态分布</h3>
            </template>
            <div ref="statusDistributionChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 平均分趋势图 -->
        <el-col :span="24">
          <el-card>
            <template #header>
              <h3>平均分趋势</h3>
            </template>
            <div ref="averageScoreTrendChart" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 课程平均分排行 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <h3>课程平均分排行 (前10名)</h3>
            </template>
            <div ref="courseAverageChart" style="height: 400px;"></div>
          </el-card>
        </el-col>
        
        <!-- 专业平均分统计 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <h3>专业平均分统计</h3>
            </template>
            <div ref="departmentAverageChart" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 成绩列表 -->
    <div class="grade-table">
      <el-card>
        <template #header>
          <h3>成绩列表</h3>
        </template>
        
        <el-table :data="gradeList" style="width: 100%" v-loading="loading">
          <el-table-column prop="studentNo" label="学号" width="120" />
          <el-table-column prop="studentName" label="学生姓名" width="120" />
          <el-table-column prop="courseName" label="课程名称" width="150" />
          <el-table-column prop="teacherName" label="教师姓名" width="120" />
          <el-table-column prop="academicYear" label="学年" width="100" />
          <el-table-column prop="semester" label="学期" width="100" />
          <el-table-column prop="usualScore" label="平时成绩" width="100">
            <template #default="scope">
              <span v-if="scope.row.usualScore">{{ scope.row.usualScore }}</span>
              <span v-else class="text-muted">未录入</span>
            </template>
          </el-table-column>
          <el-table-column prop="examScore" label="考试成绩" width="100">
            <template #default="scope">
              <span v-if="scope.row.examScore">{{ scope.row.examScore }}</span>
              <span v-else class="text-muted">未录入</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalScore" label="总成绩" width="100">
            <template #default="scope">
              <span v-if="scope.row.totalScore">{{ scope.row.totalScore }}</span>
              <span v-else class="text-muted">未计算</span>
            </template>
          </el-table-column>
          <el-table-column prop="letterGrade" label="等级" width="80">
            <template #default="scope">
              <el-tag 
                v-if="scope.row.letterGrade"
                :type="getGradeTagType(scope.row.letterGrade)"
                size="small"
              >
                {{ scope.row.letterGrade }}
              </el-tag>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.updateTime) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getAllGrades, getGradeStatistics, getGradeDistribution, getAverageScoreTrend, getCourseAverageScores, getDepartmentAverageScores } from '@/api/grade'
    const loading = ref(false)
    const gradeList = ref([])
    const statistics = ref({})
    
    // 图表实例
    const gradeDistributionChart = ref(null)
    const statusDistributionChart = ref(null)
    const averageScoreTrendChart = ref(null)
    const courseAverageChart = ref(null)
    const departmentAverageChart = ref(null)
    
    // 图表对象
    let gradeDistributionChartInstance = null
    let statusDistributionChartInstance = null
    let averageScoreTrendChartInstance = null
    let courseAverageChartInstance = null
    let departmentAverageChartInstance = null

    // 搜索参数
    const searchParams = reactive({
      academicYear: '',
      semester: '',
      courseName: '',
      studentName: '',
      teacherName: '',
      status: null
    })

    // 分页参数
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 获取成绩列表
    const loadGrades = async () => {
      try {
        loading.value = true
        const response = await getAllGrades({
          ...searchParams,
          pageNum: pagination.current,
          pageSize: pagination.size
        })
        
        gradeList.value = response.data.records || []
        pagination.total = response.data.total || 0
      } catch (error) {
        console.error('获取成绩列表失败:', error)
        ElMessage.error('获取成绩列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取统计数据
    const loadStatistics = async () => {
      try {
        const response = await getGradeStatistics({
          academicYear: searchParams.academicYear,
          semester: searchParams.semester
        })
        
        statistics.value = response.data || {}
      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.error('获取统计数据失败')
      }
    }

    // 初始化成绩等级分布图
    const initGradeDistributionChart = async () => {
      try {
        const response = await getGradeDistribution({
          academicYear: searchParams.academicYear,
          semester: searchParams.semester
        })
        
        const data = response.data || []
        const gradeColors = {
          'A': '#67C23A',
          'B': '#409EFF',
          'C': '#E6A23C',
          'D': '#F56C6C',
          'F': '#909399'
        }
        
        const chartData = data.map(item => ({
          name: `${item.grade}等级`,
          value: item.count,
          itemStyle: { color: gradeColors[item.grade] || '#909399' }
        }))

        if (!gradeDistributionChartInstance) {
          gradeDistributionChartInstance = echarts.init(gradeDistributionChart.value)
        }

        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '成绩等级分布',
              type: 'pie',
              radius: '50%',
              data: chartData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }

        gradeDistributionChartInstance.setOption(option)
      } catch (error) {
        console.error('获取成绩等级分布失败:', error)
      }
    }

    // 初始化状态分布图
    const initStatusDistributionChart = () => {
      const statusData = statistics.value.statusDistribution || []
      const statusColors = {
        0: '#909399',
        1: '#67C23A',
        2: '#E6A23C',
        3: '#409EFF',
        4: '#F56C6C'
      }
      
      const statusNames = {
        0: '草稿',
        1: '已保存',
        2: '待审核',
        3: '已通过',
        4: '已退回'
      }
      
      const chartData = statusData.map(item => ({
        name: statusNames[item.status] || '未知',
        value: item.count,
        itemStyle: { color: statusColors[item.status] || '#909399' }
      }))

      if (!statusDistributionChartInstance) {
        statusDistributionChartInstance = echarts.init(statusDistributionChart.value)
      }

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '成绩状态分布',
            type: 'pie',
            radius: '50%',
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

      statusDistributionChartInstance.setOption(option)
    }

    // 初始化平均分趋势图
    const initAverageScoreTrendChart = async () => {
      try {
        const response = await getAverageScoreTrend()
        const data = response.data || []
        
        const categories = data.map(item => `${item.academicYear} ${item.semester}`)
        const scores = data.map(item => item.averageScore)
        const counts = data.map(item => item.studentCount)

        if (!averageScoreTrendChartInstance) {
          averageScoreTrendChartInstance = echarts.init(averageScoreTrendChart.value)
        }

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: ['平均分', '学生数量']
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: categories
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '平均分',
              min: 0,
              max: 100,
              position: 'left'
            },
            {
              type: 'value',
              name: '学生数量',
              position: 'right'
            }
          ],
          series: [
            {
              name: '平均分',
              type: 'line',
              stack: 'Total',
              smooth: true,
              lineStyle: {
                width: 3
              },
              showSymbol: true,
              areaStyle: {
                opacity: 0.3
              },
              emphasis: {
                focus: 'series'
              },
              data: scores
            },
            {
              name: '学生数量',
              type: 'line',
              yAxisIndex: 1,
              smooth: true,
              lineStyle: {
                width: 2,
                type: 'dashed'
              },
              showSymbol: true,
              emphasis: {
                focus: 'series'
              },
              data: counts
            }
          ]
        }

        averageScoreTrendChartInstance.setOption(option)
      } catch (error) {
        console.error('获取平均分趋势失败:', error)
      }
    }

    // 初始化课程平均分图
    const initCourseAverageChart = async () => {
      try {
        const response = await getCourseAverageScores({
          academicYear: searchParams.academicYear,
          semester: searchParams.semester,
          limit: 10
        })
        
        const data = response.data || []
        const courseNames = data.map(item => item.courseName)
        const averageScores = data.map(item => item.averageScore)

        if (!courseAverageChartInstance) {
          courseAverageChartInstance = echarts.init(courseAverageChart.value)
        }

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const item = data[params[0].dataIndex]
              return `课程：${item.courseName}<br/>
                      教师：${item.teacherName}<br/>
                      平均分：${item.averageScore}<br/>
                      学生数：${item.studentCount}<br/>
                      最高分：${item.maxScore}<br/>
                      最低分：${item.minScore}`
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            type: 'category',
            data: courseNames
          },
          series: [
            {
              name: '平均分',
              type: 'bar',
              data: averageScores,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }
          ]
        }

        courseAverageChartInstance.setOption(option)
      } catch (error) {
        console.error('获取课程平均分失败:', error)
      }
    }

    // 初始化专业平均分图
    const initDepartmentAverageChart = async () => {
      try {
        const response = await getDepartmentAverageScores({
          academicYear: searchParams.academicYear,
          semester: searchParams.semester
        })
        
        const data = response.data || []
        const departments = data.map(item => item.department)
        const averageScores = data.map(item => item.averageScore)

        if (!departmentAverageChartInstance) {
          departmentAverageChartInstance = echarts.init(departmentAverageChart.value)
        }

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const item = data[params[0].dataIndex]
              return `专业：${item.department}<br/>
                      平均分：${item.averageScore}<br/>
                      学生数：${item.studentCount}<br/>
                      A等级：${item.gradeA}人<br/>
                      B等级：${item.gradeB}人<br/>
                      C等级：${item.gradeC}人<br/>
                      D等级：${item.gradeD}人<br/>
                      F等级：${item.gradeF}人`
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: departments,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '平均分'
          },
          series: [
            {
              name: '平均分',
              type: 'bar',
              data: averageScores,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }
          ]
        }

        departmentAverageChartInstance.setOption(option)
      } catch (error) {
        console.error('获取专业平均分失败:', error)
      }
    }

    // 初始化所有图表
    const initCharts = async () => {
      await nextTick()
      await initGradeDistributionChart()
      initStatusDistributionChart()
      await initAverageScoreTrendChart()
      await initCourseAverageChart()
      await initDepartmentAverageChart()
    }

    // 搜索成绩
    const searchGrades = () => {
      pagination.current = 1
      loadGrades()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchParams, {
        academicYear: '',
        semester: '',
        courseName: '',
        studentName: '',
        teacherName: '',
        status: null
      })
      pagination.current = 1
      loadGrades()
    }

    // 刷新统计
    const refreshStatistics = async () => {
      await loadStatistics()
      await initCharts()
      ElMessage.success('统计数据已刷新')
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      loadGrades()
    }

    const handleCurrentChange = (val) => {
      pagination.current = val
      loadGrades()
    }

    // 工具函数
    const getStatusText = (status) => {
      const statusMap = {
        0: '草稿',
        1: '已保存',
        2: '已送审',
        3: '已审核通过',
        4: '已审核退回'
      }
      return statusMap[status] || '未知'
    }

    const getStatusTagType = (status) => {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'primary',
        4: 'danger'
      }
      return typeMap[status] || 'info'
    }

    const getGradeTagType = (grade) => {
      const typeMap = {
        'A': 'success',
        'B': 'primary',
        'C': 'warning',
        'D': 'danger',
        'F': 'danger'
      }
      return typeMap[grade] || 'info'
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    // 窗口大小调整
    const handleResize = () => {
      if (gradeDistributionChartInstance) gradeDistributionChartInstance.resize()
      if (statusDistributionChartInstance) statusDistributionChartInstance.resize()
      if (averageScoreTrendChartInstance) averageScoreTrendChartInstance.resize()
      if (courseAverageChartInstance) courseAverageChartInstance.resize()
      if (departmentAverageChartInstance) departmentAverageChartInstance.resize()
    }

    onMounted(async () => {
      await loadStatistics()
      await loadGrades()
      await initCharts()
      
      window.addEventListener('resize', handleResize)
    })
</script>

<style scoped>
.grade-statistics {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.filter-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.approved {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.rejected {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-section {
  margin-bottom: 20px;
}

.grade-table {
  background: #fff;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-muted {
  color: #c0c4cc;
}

:deep(.el-card__header) {
  padding: 18px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

:deep(.el-card__header h3) {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
</style> 